<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- treetable区域 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :show-row-hover="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <template slot="daan" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color:green"></i>
          <i class="el-icon-error" v-if="scope.row.cat_deleted === true" style="color:red"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level===1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scoped">
          <el-button size="mini" type="primary" @click="editButon(scoped.row.cat_id)">编辑</el-button>
          <el-button size="mini" type="danger" @click="editButonDelete(scoped.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      @close="CateFormClosed"
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
    >
      <!-- 添加分类表单 -->
      <el-form
        ref="addCateFormRef"
        :model="addCateForm"
        :rules="addCateFormRules"
        label-width="80px"
      >
        <el-form-item label="分支名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChange"
            clearable
            popper-class
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- d编辑按钮对话框-->
    <el-dialog title="修改分类" :visible.sync="editDialogVisible" width="50%" @close="dialogClosed">
      <el-form ref="editDataRef" :model="editData" label-width="80px" :rules="addCateFormRules">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editData.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="settingEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import '../custom/message.js'
export default {
  data() {
    return {
      cateList: [],
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
          //   align: 'center'
          headerAlign: 'center'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'daan',
          align: 'center',
          headerAlign: 'center'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order',
          align: 'center',
          headerAlign: 'center'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt',
          align: 'center',
          headerAlign: 'center'
        }
      ],
      addCateDialogVisible: false,
      addCateForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      //   表单验证规则
      addCateFormRules: {
        cat_name: {
          required: true,
          message: '请输入活动名称',
          trigger: 'blur'
        }
      },
      parentCateList: [],
      //   指定级联的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedKeys: [],
      editDialogVisible: false,
      editData: {}
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取商品列表失败')
      this.$msg('获取商品列表成功', 'success')

      //   console.log(res)
      this.cateList = res.data.result
      this.total = res.data.total
      //   console.log(this.cateList)
    },
    handleSizeChange(newSize) {
      //   console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(newPage) {
      //   console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    // 展开添加分类对话框
    showCateDialog() {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    //获取父级分类数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) this.$msg('获取商品分类列表失败')
      this.$msg('获取成功', 'seccess')
      this.parentCateList = res.data
      console.log(this.parentCateList)
    },
    CateFormClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    // 获取父级分类
    parentCateChange() {
      console.log(this.selectedKeys)
      //   如果用户选择了父级分类
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        // level也随之发生变化
        this.addCateForm.cat_level = this.selectedKeys.length
        return
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
        return
      }
    },
    addCate() {
      console.log(this.addCateForm)
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        //发送请求完成添加分类
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )

        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败')
        }

        this.$message.success('添加分类成功')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    // 编辑按钮
    async editButon(id) {
      //   console.log(id)
      const { data: res } = await this.$http.get('categories/' + id)
      //   console.log(res)
      if (res.meta.status !== 200) return this.$msg('根据id查询分类失败')

      this.editData = res.data
      this.editDialogVisible = true
    },
    dialogClosed() {
      this.$refs.editDataRef.resetFields()
      this.editData = {}
    },
    settingEdit() {
      this.$refs.editDataRef.validate(async valid => {
        if (!valid) return this.$msg('请输入合法的分类名称')
        const { data: res } = await this.$http.put(
          'categories/' + this.editData.cat_id,
          this.editData
        )
        console.log(res)
        if (res.meta.status !== 200) return this.$msg('提交编辑分类失败')
        this.$msg('提交分类成功', 'success')
        this.getCateList()
        console.log(this.editData)
        this.editDialogVisible = false
      })
    },
    // 删除分类按钮

    async editButonDelete(id) {
      const confirmDelete = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmDelete !== 'confirm') return this.$msg('已取消删除')
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) return this.$msg('删除失败')
      this.getCateList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>